package net.jxtz.jxtzos.controller.landtax;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.landtax.Residential;
import net.jxtz.jxtzos.entity.web.R;
import net.jxtz.jxtzos.landtax.ExcelListener;
import net.jxtz.jxtzos.landtax.TableHeader;
import net.jxtz.jxtzos.service.landtax.ResidentialService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author a123
 */
@RestController
@RequestMapping("/residential")
@CrossOrigin
@Slf4j
public class ResidentialController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R add(@RequestBody Residential residential){
        boolean save = residentialService.save(residential);
        return save ? R.ok():R.error();
    }

    @SneakyThrows
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public R upload(MultipartFile file) {
        EasyExcel.read(file.getInputStream(), Residential.class, new ExcelListener(residentialService)).sheet().doRead();
        return R.ok();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R delete(@PathVariable Long id){
        boolean b = residentialService.removeById(id);
        return b ? R.ok():R.error();
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public R list(){
        List<Residential> list = residentialService.list();
        return R.ok().data("list", list);
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize){
        Page<Residential> page = residentialService.page(new Page<>(pageNum, pageSize));
        List<Residential> records = page.getRecords();
        long total = page.getTotal();
        return R.ok().data("total", total).data("list", records);
    }


    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public R search(@RequestBody SearchVo searchVo,
                    @RequestParam("pageNum") Integer pageNum,
                    @RequestParam("pageSize") Integer pageSize){
        QueryWrapper<Residential> residentialQueryWrapper = new QueryWrapper<>();
        String[] s = searchVo.getSearchContent().split(" ");
        if(searchVo.getHousingType()!=null && searchVo.getHousingType()!=""){
            residentialQueryWrapper.eq("house_type",searchVo.getHousingType());
        }
        if (!"".equals(s[0])){
            // 楼栋名和编号
            residentialQueryWrapper.and(wrapper ->
                    wrapper.like("building_name", s[0])
                    .or()
                    // 小区名
                    .like("village", s[0])
                    .or()
                    // 前台匹配
                    .like("land_tax_matching", s[0]));
                    // 楼栋名
        }

        List<Residential> list = residentialService.list(residentialQueryWrapper);
        if (s.length > 1){
            list = list.stream().filter(residential -> residential.getFloor().equals(s[1])).collect(Collectors.toList());
        }

        int size = list.size();
        list = list.stream().skip((long) pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());
        return R.ok().data("list", list).data("total", size);
    }

    @SneakyThrows
    @RequestMapping(value = "/excel_download", method = RequestMethod.POST)
    public void excelDownload(HttpServletResponse response){
        List<Residential> list = residentialService.list();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("南昌市住宅地税前台", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Residential.class).sheet("1").doWrite(list);
    }


    @RequestMapping(value = "/list_header", method = RequestMethod.GET)
    public R listHeader(){
        return R.ok().data("list", TableHeader.getListHeader());
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public R update(@RequestBody Residential residential){
        boolean b = residentialService.updateById(residential);
        return b ? R.ok():R.error();
    }

    private final ResidentialService residentialService;

    public ResidentialController(ResidentialService residentialService){
        this.residentialService = residentialService;
    }

}
